package me.zhengjie.modules.security.service;

import lombok.RequiredArgsConstructor;
import me.zhengjie.utils.RedisUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 在线用户服务
 */
@Service
@RequiredArgsConstructor
public class OnlineUserService {

    private final RedisUtils redisUtils;
    private final TokenProvider tokenProvider;

    /**
     * 保存在线用户
     */
    public void save(UserDetails jwtUserDto, String token, HttpServletRequest request) {
        String ip = request != null ? getIp(request) : "unknown";
        String key = "online-token:" + token;
        redisUtils.set(key, jwtUserDto.getUsername(), 24 * 60 * 60); // 24小时
    }

    /**
     * 根据用户名获取登录用户
     */
    public UserDetails getLoginUserByUsername(String username) {
        // 实际项目中应该从Redis中获取
        return null;
    }

    /**
     * 获取IP地址
     */
    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
} 